package com.portal.file.controller;

import com.portal.common.core.web.domain.AjaxResult;
import com.portal.file.domain.upload.FileChunkDTO;
import com.portal.file.domain.upload.FileChunkResultDTO;
import com.portal.file.service.UploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 文件上传接口
 * <p>
 *     https://blog.csdn.net/weixin_45357745/article/details/129272412
 * </p>
 */
@Slf4j
@RestController
@RequestMapping("upload")
public class UploadController {
    @Resource
    private UploadService uploadService;

    /**
     * 检查分片是否存在
     */
    @GetMapping("/chunk")
    public AjaxResult checkChunkExist(FileChunkDTO chunkDTO) {
        FileChunkResultDTO fileChunkCheckDTO;
        try {
            fileChunkCheckDTO = uploadService.checkChunkExist(chunkDTO);
            return AjaxResult.success(fileChunkCheckDTO);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 上传文件分片
     */
    @PostMapping("/chunk")
    public AjaxResult uploadChunk(FileChunkDTO chunkDTO) {
        try {
            if (uploadService.uploadChunk(chunkDTO)){
            return AjaxResult.success(chunkDTO.getIdentifier());
            }else {
                String errMsg = String.format("上传分片索引_%s/%s_错误。",chunkDTO.getChunkNumber(),chunkDTO.getTotalChunks());
                return AjaxResult.error(errMsg);
            }
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 完成上传
     */
    @PostMapping("/multipart/merge")
    public AjaxResult completeMultiPartUpload(@RequestBody FileChunkDTO fileChunkDTO) {
        log.info("REST: 通过 <{}> 合并上传任务", fileChunkDTO);
        return uploadService.mergeChunk(fileChunkDTO.getIdentifier(),fileChunkDTO.getFilename(),fileChunkDTO.getTotalChunks());
    }

}
